<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="back-btn" @click="handleBack">
				<text class="iconfont">&#xe6ff;</text>
				<text>返回</text>
			</view>
			<text class="title">我的订单</text>
		</view>

		<!-- 调试信息（开发环境显示） -->
		<view class="debug-info" v-if="showDebugInfo">
			<text class="debug-text">当前用户ID: {{ currentUserId }}</text>
			<text class="debug-text">登录状态: {{ isLoggedIn ? '已登录' : '未登录' }}</text>
		</view>

		<!-- 订单分类标签 -->
		<view class="tabs">
			<view class="tab-item" :class="{ active: activeTab === 0 }" @click="switchTab(0)">
				历史订单
			</view>
			<view class="tab-item" :class="{ active: activeTab === 1 }" @click="switchTab(1)">
				未支付订单
			</view>
		</view>

		<!-- 订单列表 -->
				<scroll-view class="order-list" scroll-y @scroll="onScroll" :scroll-top="scrollTop">
					<!-- 历史订单 -->
					<view v-if="activeTab === 0" class="tab-content">
						<view v-for="(item, index) in historyOrders" :key="index" class="order-item">
							<text class="order-no">订单号：{{ item.orderId }}</text>
							<text class="order-time">{{ formatDate(item.createTime) }}</text>
							<text class="order-amount">￥{{ item.totalAmount }}</text>
							<text class="order-status">{{ item.orderStatus }}</text>
							<view class="dish-list">
								<view v-for="(dish, i) in item.dishDetails" :key="i" class="dish-item">
									<text>{{ dish.dishName }} ×{{ dish.quantity }}</text>
									<text>￥{{ dish.subtotal }}</text>
								</view>
							</view>
						</view>
						<text v-if="historyOrders.length === 0" class="empty-tip">暂无历史订单</text>
					</view>

			<!-- 未支付订单 -->
			<view v-if="activeTab === 1" class="tab-content">
				<view v-for="(item, index) in unpaidOrders" :key="index" class="order-item">
					<text class="order-no">订单号：{{ item.orderId }}</text>
					<text class="trade-no">交易号：{{ item.tradeNo }}</text>
					<text class="order-time">创建时间：{{ formatDate(item.createTime) }}</text>
					<text class="order-amount unpaid">￥{{ (item.amount || 0).toFixed(2) }}</text>
					<text class="order-status">状态：{{ getStatusText(item.status) }}</text>
					
					<!-- 调试信息 -->
					<view class="debug-amount" style="font-size: 20rpx; color: #999; margin-top: 10rpx;">
						<text>计算金额: ￥{{ (item.calculatedAmount || 0).toFixed(2) }} | </text>
						<text>后端金额: ￥{{ (item.backendAmount || 0).toFixed(2) }}</text>
					</view>
					
					<!-- 解析订单详情 -->
					<view class="dish-list">
						<view v-for="(dish, i) in parseOrderDetails(item.orderDetail)" :key="i" class="dish-item">
							<view class="dish-info">
								<text class="dish-name">{{ dish.dishName }}</text>
								<text class="dish-spec" v-if="dish.specText">{{ dish.specText }}</text>
							</view>
							<view class="dish-quantity">
								<text>×{{ dish.quantity }}</text>
								<text>￥{{ (dish.price * dish.quantity).toFixed(2) }}</text>
							</view>
						</view>
					</view>
					
					<button v-if="item.status === 0" class="pay-btn" @click="handlePay(item)">立即支付</button>
				</view>
				<text v-if="unpaidOrders.length === 0" class="empty-tip">暂无未支付订单</text>
			</view>
		</scroll-view>

		<!-- 返回顶部按钮 -->
		<up-back-top :scroll-top="scrollTop" :custom-style="backTopStyle"></up-back-top>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onPageScroll,
		onLoad
	} from '@dcloudio/uni-app';
	import {
		order,
		orderss
	} from '@/api/order.js';
	import { payOrder } from '@/api/orderFoods.js';

	// 滚动位置
	const scrollTop = ref(0);
	const onScroll = (e) => {
		scrollTop.value = e.detail.scrollTop;
	};

	// 返回顶部按钮样式
	const backTopStyle = {
		bottom: '100rpx',
		right: '30rpx',
		zIndex: 999
	};

	// 顶部返回
	const handleBack = () => {
		uni.navigateBack();
	};

	// 订单标签切换
	const activeTab = ref(0);
	const switchTab = (index) => {
		activeTab.value = index;
		scrollTop.value = 0;
	};

	// 订单数据
	const historyOrders = ref([]);
	const unpaidOrders = ref([]);

	// 调试信息
	const showDebugInfo = ref(true); // 开发环境显示调试信息
	const currentUserId = ref(0);
	const isLoggedIn = ref(false);

	// 格式化日期
	const formatDate = (dateString) => {
		if (!dateString) return '';
		const date = new Date(dateString);
		return `${date.getFullYear()}-${padZero(date.getMonth()+1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
	};

	const padZero = (num) => {
		return num < 10 ? `0${num}` : num;
	};

	// 解析订单详情
	const parseOrderDetails = (orderDetail) => {
		try {
			if (typeof orderDetail === 'string') {
				return JSON.parse(orderDetail);
			}
			return orderDetail || [];
		} catch (e) {
			console.error('解析订单详情失败:', e);
			return [];
		}
	};

	// 获取状态文本
	const getStatusText = (status) => {
		const statusMap = {
			0: '未支付',
			1: '已支付',
			2: '已取消',
			3: '已完成'
		};
		return statusMap[status] || '未知状态';
	};

	// 支付操作
	const handlePay = (order) => {
		uni.showModal({
			title: '支付确认',
			content: `确认支付订单 ${order.orderId} ￥${order.amount.toFixed(2)} 吗？`,
			success(res) {
				if (res.confirm) {
					// 调用真实的支付API
					handleRealPayment(order);
				}
			}
		});
	};

	// 真实支付处理
	const handleRealPayment = async (order) => {
		try {
			uni.showLoading({
				title: '支付处理中...'
			});

			console.log('开始支付订单:', order);
			console.log('支付订单号:', order.tradeNo);

			// 调用支付API
			const response = await payOrder(order.tradeNo);

			uni.hideLoading();
			console.log('支付API响应:', response);

			// 根据后端PayController的响应格式处理
			// 成功时: { code: 200, data: {}, message: "支付成功！！！", success: true }
			// 失败时: { code: 非200, message: "错误信息" }
			console.log('支付响应详细分析:');
			console.log('- response:', response);
			console.log('- response.code:', response.code);
			console.log('- response.message:', response.message);
			console.log('- response.success:', response.success);
			
			if (response && response.code === 200 && response.message) {
				if (response.message.includes('支付成功')) {
					uni.showToast({
						title: '支付成功',
						icon: 'success',
						duration: 2000
					});

					// 支付成功后刷新订单列表
					setTimeout(() => {
						fetchOrders();
						fetchOrderss();
						
						// 触发个人中心数据更新
						uni.$emit('userStatsUpdated');
					}, 1000);
				} else {
					uni.showToast({
						title: response.message,
						icon: 'none',
						duration: 2000
					});
				}
			} else if (response && response.message) {
				// 支付失败的情况
				uni.showToast({
					title: response.message,
					icon: 'none',
					duration: 2000
				});
			} else {
				uni.showToast({
					title: '支付响应格式异常',
					icon: 'none',
					duration: 2000
				});
				console.error('异常的支付响应:', response);
			}

		} catch (error) {
			uni.hideLoading();
			console.error('支付过程出错:', error);
			
			uni.showToast({
				title: error.message || '支付失败，请重试',
				icon: 'none',
				duration: 2000
			});
		}
	};

	// 获取历史订单
	const fetchOrders = async () => {
		try {
			// 获取用户ID
			const userId = uni.getStorageSync('userId');
			if (!userId) {
				console.warn('未找到用户ID，无法获取历史订单');
				uni.showToast({
					title: '请先登录',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			
			console.log('准备获取历史订单，userId:', userId);
			
			const res = await order({ userId });
			console.log('历史订单响应:', res);
			
			if (res && res.list) {
				const allOrders = res.list || [];
				historyOrders.value = allOrders.filter(item => item.orderStatus === '已支付');
				console.log('过滤后的历史订单:', historyOrders.value);
			} else {
				console.log('没有获取到历史订单数据，使用模拟数据');
				// 如果没有数据，显示模拟数据
				historyOrders.value = generateMockHistoryOrders();
			}
		} catch (error) {
			console.error('获取历史订单失败:', error);
			console.error('错误详情:', error);
			// API调用失败时显示模拟数据
			historyOrders.value = generateMockHistoryOrders();
		}
	};

	// 获取未支付订单
	const fetchOrderss = async () => {
		try {
			// 获取用户ID
			const userId = uni.getStorageSync('userId');
			if (!userId) {
				console.warn('未找到用户ID，无法获取未支付订单');
				uni.showToast({
					title: '请先登录',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			
			console.log('准备获取未支付订单，userId:', userId);
			
			const res = await orderss({ userId });
			console.log('未支付订单响应:', res);
			
			if (res && res.list) {
				console.log('原始未支付订单数据:', res.list);
				
				unpaidOrders.value = res.list.map(item => {
					// 解析订单详情计算总金额
					const orderDetails = parseOrderDetails(item.orderDetail);
					const calculatedAmount = orderDetails.reduce((total, dish) => {
						return total + (dish.price * dish.quantity);
					}, 0);
					
					return {
						...item,
						amount: calculatedAmount || item.amount || 0, // 优先使用计算的金额，否则使用后端返回的金额
						calculatedAmount: calculatedAmount,
						backendAmount: item.amount
					};
				});
				
				console.log('处理后的未支付订单:', unpaidOrders.value);
				console.log('未支付订单详细信息:', unpaidOrders.value.map(item => ({
					orderId: item.orderId,
					tradeNo: item.tradeNo,
					amount: item.amount,
					calculatedAmount: item.calculatedAmount,
					backendAmount: item.backendAmount,
					status: item.status,
					orderDetail: item.orderDetail
				})));
			} else {
				console.log('没有获取到未支付订单数据，使用模拟数据');
				// 如果没有数据，显示模拟数据
				unpaidOrders.value = generateMockUnpaidOrders();
			}
		} catch (e) {
			console.error('获取未支付订单失败:', e);
			console.error('错误详情:', e);
			// API调用失败时显示模拟数据
			unpaidOrders.value = generateMockUnpaidOrders();
		}
	};

	// 生成模拟历史订单数据
	const generateMockHistoryOrders = () => {
		return [
			{
				orderId: 'ORD' + Date.now(),
				createTime: new Date(Date.now() - 86400000).toISOString(), // 1天前
				totalAmount: 68.50,
				orderStatus: '已支付',
				dishDetails: [
					{ dishName: '宫保鸡丁', quantity: 1, subtotal: 28.00 },
					{ dishName: '麻婆豆腐', quantity: 1, subtotal: 18.00 },
					{ dishName: '米饭', quantity: 2, subtotal: 4.00 }
				]
			},
			{
				orderId: 'ORD' + (Date.now() - 1000),
				createTime: new Date(Date.now() - 172800000).toISOString(), // 2天前
				totalAmount: 45.00,
				orderStatus: '已支付',
				dishDetails: [
					{ dishName: '红烧肉', quantity: 1, subtotal: 38.00 },
					{ dishName: '青菜', quantity: 1, subtotal: 12.00 }
				]
			}
		];
	};

	// 生成模拟未支付订单数据
	const generateMockUnpaidOrders = () => {
		const mockOrderDetail = [
			{ dishName: '糖醋里脊', quantity: 1, price: 32.00, specText: '规格:大份' },
			{ dishName: '米饭', quantity: 2, price: 2.00, specText: '' }
		];
		const calculatedAmount = mockOrderDetail.reduce((total, dish) => total + (dish.price * dish.quantity), 0);
		
		return [
			{
				orderId: 'ORD' + (Date.now() + 1000),
				tradeNo: 'ORDER' + Date.now(),
				createTime: new Date().toISOString(),
				amount: calculatedAmount, // 使用计算出的金额
				calculatedAmount: calculatedAmount,
				backendAmount: 36.00, // 模拟后端返回的金额
				status: 0,
				orderDetail: JSON.stringify(mockOrderDetail)
			}
		];
	};

	// 页面加载时获取数据
	onMounted(() => {
		// 初始化调试信息
		const loggedUserId = uni.getStorageSync('userId');
		currentUserId.value = loggedUserId;
		isLoggedIn.value = !!loggedUserId;
		
		console.log('订单页面初始化，用户信息:', {
			loggedUserId,
			currentUserId: currentUserId.value,
			isLoggedIn: isLoggedIn.value
		});
		
		fetchOrders();
		fetchOrderss();
	});
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f7f7f7;
	}

	.header {
		height: 90rpx;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		background-color: #fff;
		position: relative;
		border-bottom: 1rpx solid #eee;

		.back-btn {
			display: flex;
			align-items: center;
			font-size: 28rpx;
			color: #666;

			.iconfont {
				margin-right: 10rpx;
				font-size: 36rpx;
			}
		}

		.title {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			font-size: 36rpx;
			font-weight: bold;
		}
	}

	.debug-info {
		background-color: #f0f8ff;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #ddd;

		.debug-text {
			display: block;
			font-size: 24rpx;
			color: #666;
			margin-bottom: 8rpx;

			&:last-child {
				margin-bottom: 0;
			}
		}
	}

	.tabs {
		display: flex;
		height: 90rpx;
		background-color: #fff;
		margin-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;

		.tab-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 32rpx;
			color: #666;
			position: relative;

			&.active {
				color: #007aff;
				font-weight: bold;

				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 80rpx;
					height: 6rpx;
					background-color: #007aff;
					border-radius: 3rpx;
				}
			}
		}
	}

	.order-list {
		flex: 1;
		padding: 0 30rpx;
		background-color: #f7f7f7;
	}

	.tab-content {
		padding-bottom: 40rpx;
	}

	.order-item {
		background-color: #fff;
		padding: 30rpx;
		margin-bottom: 20rpx;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		position: relative;

		.order-no {
			display: block;
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 10rpx;
		}

		.trade-no {
			display: block;
			font-size: 26rpx;
			color: #999;
			margin-bottom: 10rpx;
		}

		.order-time {
			font-size: 28rpx;
			color: #999;
			margin-bottom: 15rpx;
		}

		.order-amount {
			position: absolute;
			right: 30rpx;
			top: 30rpx;
			font-size: 36rpx;
			font-weight: bold;
			color: #ff5a5f;

			&.unpaid {
				color: #f0ad4e;
			}
		}

		.order-status {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 15rpx;
		}

		.dish-list {
			border-top: 1rpx solid #eee;
			padding-top: 20rpx;
			margin-top: 20rpx;

			.dish-item {
				display: flex;
				justify-content: space-between;
				margin-bottom: 15rpx;
				padding-bottom: 15rpx;
				border-bottom: 1rpx dashed #eee;

				&:last-child {
					margin-bottom: 0;
					padding-bottom: 0;
					border-bottom: none;
				}

				.dish-info {
					flex: 1;
					display: flex;
					flex-direction: column;

					.dish-name {
						font-size: 28rpx;
						color: #333;
					}

					.dish-spec {
						font-size: 24rpx;
						color: #999;
						margin-top: 5rpx;
					}
				}

				.dish-quantity {
					display: flex;
					flex-direction: column;
					align-items: flex-end;

					text {
						font-size: 28rpx;
						color: #666;

						&:last-child {
							color: #ff5a5f;
							font-weight: bold;
						}
					}
				}
			}
		}

		.pay-btn {
			margin-top: 30rpx;
			background-color: #007aff;
			color: #fff;
			font-size: 32rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
		}
	}

	.empty-tip {
		display: block;
		text-align: center;
		margin-top: 100rpx;
		color: #999;
		font-size: 30rpx;
	}
</style>